<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <title>新增监察人员</title>
    <link rel="stylesheet" href="plugins/layui/css/layui.css" media="all" />
    <link rel="stylesheet" href="css/comments.css" media="all">
    <style>
        .layui-form-label{
            width: 110px;
        }
        @media screen and (max-width: 450px){
            .layui-form-item .layui-input-inline {
                margin-left: 140px;
            }
        }
        .layui-input-block{
            margin-left: 140px;
        }
        #tableForm{
            padding: 10px 20px;
            display: none;

        }
    </style>
</head>
<body>
    <div class="maincontainer">
        <blockquote class="layui-elem-quote">
            新增监察人员
            <button type="button" class="layui-btn layui-btn-sm" style="float: right;margin-top: -4px;" onclick="window.history.back();">返回</button>
        </blockquote>
        <form class="layui-form" action="" lay-filter="example">
            <div class="layui-form-item">
                <label class="layui-form-label">账号：</label>
                <div class="layui-input-inline">
                  <input type="text" name="account" autocomplete="off" placeholder="请输入账号" class="layui-input" maxlength="20" readonly onfocus="this.removeAttribute('readonly');" onblur="this.setAttribute('readonly',true);">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">密码：</label>
                <div class="layui-input-inline">
                    <input type="password" name="password" placeholder="请输入密码" autocomplete="off" class="layui-input" maxlength="20">
                </div>
                <div class="layui-form-mid layui-word-aux">注：6到20位字母或数字</div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">确认密码：</label>
                <div class="layui-input-inline">
                    <input type="password" name="password1" placeholder="请输入确认密码" autocomplete="off" class="layui-input" maxlength="20">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">姓名：</label>
                <div class="layui-input-inline">
                  <input type="text" name="name" autocomplete="off" placeholder="请输入姓名" class="layui-input" maxlength="20">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">性别：</label>
                <div class="layui-input-block">
                    <input type="radio" name="sex" value="1" title="男" checked="">
                    <input type="radio" name="sex" value="2"" title="女">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">分配食堂：</label>
                <div class="layui-input-inline">
                    <button type="button" class="layui-btn selectCanteen" >选择食堂</button>
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label"></label>
                <div class="layui-input-block">
                    <table class="layui-hide" id="canteenTable" lay-filter="canteenTable"></table>
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">状态：</label>
                <div class="layui-input-block">
                    <input type="radio" name="openStatus" value="1" title="启用" checked="">
                    <input type="radio" name="openStatus" value="0" title="禁用">
                </div>
            </div>
            <div class="layui-form-item">
              <div class="layui-input-block">
                <button type="button" class="layui-btn" lay-submit="" lay-filter="demo1">确认</button>
                <button type="button" class="layui-btn layui-btn-primary" onclick="window.history.back()">取消</button>
              </div>
            </div>
        </form>
    </div>
    <div id="tableForm">
        <div class="layui-form-item">
            <label class="layui-form-label">食堂名称：</label>
            <div class="layui-input-inline">
              <input type="text" name="canteenName" autocomplete="off" placeholder="食堂名称" class="layui-input" maxlength="20">
            </div>
            <div class="layui-inline">
                <button type="button" class="layui-btn searchCanteen" >查询</button>
            </div>
        </div>
        <table class="layui-hide" id="selectTable" lay-filter="selectTable"></table>
    </div>
<script type="text/javascript" src="plugins/layui/layui.js"></script>
<script type="text/javascript" src="js/jquery.min.js"></script>
<script>

    layui.config({
        base: 'plugins/layui/modules/',
    }).use(['http', 'form', 'table'], function() {
        var http = layui.http,
            form = layui.form,
            table = layui.table;
        var selectTable,canteenTable;
        var canteenIdSet = [] // 食堂id集合
        var canteenIdSetList = []
        var currData = [] // 当前页数据

        // 分配食堂查询
        function tableFun(){
            selectTable = http.table({
                elem: '#selectTable',
                url: 'admin/canteen/listSimplePage',
                method: 'get',
                id: 'selectTable',
                height: 300,
                done: function(res, curr, count){
                    var data = res.data;
                    currData = data
                    data.forEach(function(value, key) {
                    //这里必须选择点击方法，不知为何添加layui-form-checked class属性会造成二次点击（即下次点击必须点击两下才能生效）bug，
                    //所有类似的手动修改class貌似都会造成二次效果
                        if(canteenIdSet.indexOf(value.id)!==-1){
                            value["LAY_CHECKED"]='true';
                            $("div[lay-id='selectTable'] .layui-table-body td input[type='checkbox']").eq(key).prop('checked', true)
                            $("div[lay-id='selectTable'] .layui-table-body td input[type='checkbox']").eq(key).next().addClass('layui-form-checked')
                        }
                    })
                    var checkStatus = table.checkStatus('selectTable');
                    if(checkStatus.isAll){
                        $(' .layui-table-header th[data-field="0"] input[type="checkbox"]').prop('checked', true);
                        $('.layui-table-header th[data-field="0"] input[type="checkbox"]').next().addClass('layui-form-checked');
                    }
                },
                cols: [[
                    {type:'checkbox'}
                    ,{field:'canteenName', title: '食堂名称', align : 'center'}
                    ,{field:'openStatus', title: '状态', align : 'center',
                        templet: function (d) {
                            return d.openStatus==1?'启用':'禁用';
                        }
                    }
                ]]
            });
            table.on('checkbox(selectTable)', function(obj){
                var checkStatus = table.checkStatus('selectTable'); //获取选中行状态
                var data = checkStatus.data; //获取选中行数据
                for(var n=0;n<canteenIdSetList.length;n++){
                    for(var m=0;m<currData.length;m++){
                        if(canteenIdSetList[n].id == currData[m].id){
                            canteenIdSetList.splice(n,1)
                            n--
                            break
                        }
                    }
                }
                var list
                if(canteenIdSetList.length == 0){
                    list = data
                }else{
                    list = canteenIdSetList.concat(data)
                }
                canteenIdSetList = unique5(list)
                function unique5(arr){
                    canteenIdSet=[];
                    var hashList=[]
                    for (var i = 0; i < arr.length; i++) {
                        if(canteenIdSet.indexOf(arr[i].id)==-1){
                            canteenIdSet.push(arr[i].id);
                            hashList.push(arr[i])
                        }
                    }
                    return hashList;
                }
                // console.log(canteenIdSetList)

            });
        }

        // 选择食堂
        $(document).on('click','.selectCanteen',function(){
            tableFun()
            http.myOpen({
                title:'选择食堂',
                content: $('#tableForm'),
                area:['600px','500px'],
                btn:['确定','取消'],
                btn1:function(index, layero){
                    if (canteenIdSetList.length == 0) {
                        layer.msg("请勾选需要的食堂");
                        return;
                    }
                    canteenFun()
                    layer.close(index)
                }
            })
        })
        // 回显选中的食堂
        function canteenFun(){
            canteenTable = http.table1({
                elem: '#canteenTable',
                id: 'canteenTable',
                cols: [[
                    {title:'序号',type:'numbers'},
                    {field:'canteenName', title: '食堂名称', align : 'center'},
                    {field:'', title: '操作', align : 'center',fixed: 'right',width: 130,
                        templet: function (d) {
                            var html = '';
                            html += '<button type="button" class="layui-btn layui-btn-primary layui-btn-xs" lay-event="del" >删除</button>'
                            return html;
                        }
                    }
                ]],
                limit: canteenIdSetList.length,
                data: canteenIdSetList
            })

        }
        // table操作
        table.on('tool(canteenTable)', function(obj){
            if(obj.event=='del'){
                // 删除
                var index = $(obj.tr).eq(0).data('index')
                canteenIdSetList.splice(index,1)
                canteenIdSet.splice(index,1)
                canteenFun()
            }
        })
        // 查询
        $(document).on('click','.searchCanteen',function(){
            selectTable.reload({
				page:{curr:1},
				where: {
                    canteenName: $('#tableForm input[name=canteenName]').val()
                }
			})
        })

        
        //监听提交
        form.on('submit(demo1)', function(data){
            // console.log(data.field)
            if($.trim(data.field.account) == "") {
                layer.msg('请输入账号')
                return
            }
            if($.trim(data.field.password) == "") {
                layer.msg('请输入密码')
                return
            }
            if(!/^[0-9a-zA-Z]{6,20}$/.test(data.field.password)){
                layer.msg('密码不规范')
                return
            }
            if(data.field.password != data.field.password1){
                layer.msg('密码不一致')
                return
            }
            if($.trim(data.field.name) == "") {
                layer.msg('请输入姓名')
                return
            }
            if(canteenIdSet.length == 0) {
                layer.msg('请分配食堂')
                return
            }
            
            http.postJSON('admin/observer/add',JSON.stringify({
                account: $.trim(data.field.account),
                password: data.field.password,
                name: data.field.name,
                sex: data.field.sex,
                canteenIdSet: canteenIdSet,
                openStatus: data.field.openStatus
            }),function(res){
                if(res.code == 200){
                    layer.msg('操作成功')
                    setTimeout(function(){
                        window.history.back()
                    },500)
                }else{
                    layer.msg(res.msg)
                }
            })
        });
		
		// 失焦验证密码
		$("input[name=password]").blur(function(e){
			let password1 = $('input[name=password1]').val();
			http.verifPwd($(this).val(),password1,1);
		}) 
		$("input[name=password1]").blur(function(e){
			let password = $('input[name=password]').val();
			http.verifPwd(password,$(this).val(),2);
		})
    })
</script>
</body>
</html>